<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="就诊卡列表"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />
    
    <!-- 就诊卡列表 -->
    <view class="card-list">
      <view 
        v-for="card in medicalCards" 
        :key="card.id"
        class="medical-card"
      >
        <!-- 卡片顶部 -->
        <view class="card-header">
          <view class="card-left">
            <van-icon name="cross" color="#ff4444" size="20" />
            <text class="card-title">电子健康卡</text>
          </view>
          <view class="card-right">
            <text class="card-issuer">国家卫生健康委员会监制</text>
          </view>
        </view>
        
        <!-- 卡片中间 -->
        <view class="card-middle">
          <view class="card-info-left">
            <text class="patient-name">{{ card.patientName }}</text>
            <view class="card-tag self-tag">本人</view>
          </view>
          <view class="card-info-right">
            <view class="card-tag default-tag">默认</view>
          </view>
        </view>
        
        <!-- 卡片底部 -->
        <view class="card-bottom">
          <view class="card-number">{{ formatBirthday(card.patientBirth) }}</view>
          <view class="select-btn" @click="selectCard(card)">
            <text>选择此卡</text>
            <van-icon name="arrow" />
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="medicalCards.length === 0 && !loading" class="empty-state">
        <van-empty description="暂无就诊卡" />
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <van-loading size="24px" />
        <text class="loading-text">正在加载就诊卡...</text>
      </view>
    </view>
    
    <!-- 底部添加按钮 -->
    <!-- <view class="bottom-action">
      <van-button 
        type="primary" 
        size="large" 
        block
        @click="addMedicalCard"
        class="add-card-btn"
      >
        添加就诊卡
      </van-button>
    </view> -->
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useMedicalStore } from '@/stores/modules/medical'
import { useUserStore } from '@/stores'
import type { PatientCard } from '@/api/patient'

// 就诊卡接口定义
interface MedicalCard {
  id: number
  patientName: string
  patientBirth: string
  patientGender: number
  isDefault: boolean
  isSelf: boolean
}

const medicalStore = useMedicalStore()
const userStore = useUserStore()

const loading = ref(false)

// 将后端数据转换为页面使用的格式
const medicalCards = computed(() => {
  return medicalStore.patientCards.map((card: PatientCard) => ({
    id: Number(card.patientId),
    patientName: card.patientName,
    patientBirth: card.patientBirth,
    patientGender: card.patientGender,
    isDefault: true,
    isSelf: true
  }))
})

// 格式化生日显示
const formatBirthday = (birthday: string) => {
  return `生日：${birthday}`
}

// 选择就诊卡
const selectCard = (card: MedicalCard) => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  console.log('选择就诊卡:', card)
  console.log('页面参数:', options)
  
  // 将选中的就诊卡保存到store（转换为原有格式）
  const medicalCard = {
    id: card.id,
    patientName: card.patientName,
    idNumber: '',
    maskedIdNumber: formatBirthday(card.patientBirth),
    isDefault: card.isDefault,
    isSelf: card.isSelf
  }
  medicalStore.setCurrentMedicalCard(medicalCard)
  
  // 判断是预约挂号还是在线门诊
  if (options.type === 'consultation') {
    // 在线门诊：跳转到选择病情资料页面
    const url = `/pages/online-consultation/select-medical-record?doctorId=${options.doctorId}&doctorName=${options.doctorName}&departmentName=${options.departmentName}&consultationPrice=${options.consultationPrice}`
    console.log('在线门诊跳转URL:', url)
    
    uni.navigateTo({
      url: url
    })
  } else {
    // 预约挂号：跳转到科室选择页面
    const url = `/pages/appointment/department-select`
    console.log('预约挂号跳转URL:', url)
    
    uni.navigateTo({
      url: url
    })
  }
}

// 添加就诊卡
const addMedicalCard = () => {
  uni.navigateTo({
    url: '/pages/appointment/add-medical-card'
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 加载就诊卡数据
const loadMedicalCards = async () => {
  loading.value = true
  try {
    const userId = userStore.userInfo.userId || userStore.userData.user.userId
    if (userId) {
      await medicalStore.fetchPatientCards(userId)
    } else {
      uni.showToast({ title: "用户未登录", icon: "none" })
    }
  } catch (error) {
    console.error('加载就诊卡失败:', error)
  } finally {
    loading.value = false
  }
}

// 页面加载
onLoad((options: Record<string, string>) => {
  console.log('就诊卡选择页面 onLoad', options)
  console.log('接收到的参数:', {
    doctorId: options.doctorId,
    doctorName: options.doctorName,
    departmentName: options.departmentName
  })
  
  // 从后端获取就诊卡列表
  loadMedicalCards()
})

// 页面显示时刷新数据
onMounted(() => {
  loadMedicalCards()
})
</script>

<style lang="scss" scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.card-list {
  padding: 20rpx;
}

.medical-card {
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  position: relative;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  // 添加中国结图案背景
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: 
      radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.1) 2rpx, transparent 2rpx),
      radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.1) 2rpx, transparent 2rpx),
      radial-gradient(circle at 40% 60%, rgba(255, 255, 255, 0.1) 2rpx, transparent 2rpx);
    background-size: 60rpx 60rpx, 80rpx 80rpx, 100rpx 100rpx;
    border-radius: 20rpx;
    pointer-events: none;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.card-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-issuer {
  font-size: 24rpx;
  color: #666;
  text-align: right;
}

.card-middle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.card-info-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.patient-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.card-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: white;
  
  &.self-tag {
    background: #07c160;
  }
  
  &.default-tag {
    background: #07c160;
  }
}

.card-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-number {
  font-size: 28rpx;
  color: #999;
}

.select-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: #ff6b35;
  color: white;
  padding: 16rpx 24rpx;
  border-radius: 25rpx;
  font-size: 28rpx;
  font-weight: bold;
}

.empty-state {
  padding: 100rpx 0;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #969799;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #f0f0f0;
}

.add-card-btn {
  background: #07c160;
  border: none;
  border-radius: 25rpx;
  height: 88rpx;
  font-size: 32rpx;
  font-weight: bold;
}
</style>
